package com.zf.bm.common.core.shiro.utils;

import com.zf.bm.common.core.sys.entity.Login;
import com.zf.bm.common.utils.CacheUtils;
import io.jsonwebtoken.*;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.Date;


@Slf4j
public class ShiroUtils {

    /**
     * JWT签发令牌
     */
    public static String createToken(Login login){
        long currentTimeMillis = System.currentTimeMillis();
        JwtBuilder jwt = Jwts.builder();
        String sessionId = getSession().getId().toString();
        jwt.setId(sessionId);
        //用户名
        jwt.setSubject(login.getUserName());
        //签发者
        jwt.setIssuer("ZFINFO");
        //签发时间
        jwt.setIssuedAt(new Date(currentTimeMillis));
        //有效时间
        //客户端ua
        String ua ="";
        jwt.claim("ua",ua);
        jwt.compressWith(CompressionCodecs.DEFLATE);
        jwt.signWith(SignatureAlgorithm.ES512,"njzfbm");
        String token = jwt.compact();
        CacheUtils.putToken(token,currentTimeMillis);
        return token;
    }

    /**
     * 验签JWT
     */
    public static Claims parseToken(String token){
        log.info("验证Token:[{}]",token);
        if (StringUtils.isBlank(token)){
            return null;
        }
        token = token.replace("Bearer", "");
        return Jwts.parser()
                .setSigningKey("njzfbm")
                .parseClaimsJws(token)
                .getBody();
    }

    public static String getToken(ServletRequest req){
        HttpServletRequest request = (HttpServletRequest)req;
//        request.getHeader(Constant.)
    }

    /**
     * 获取当前登录用户session
     *
     */
    public static Session getSession() {
        return getSubject().getSession();
    }

    /**
     * 获取当前Subject
     *
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }
}
